import React from 'react';
import { Table, Pagination } from 'antd';
import styles from './index.less';
import request from 'umi-request';
import { useEffect, useState } from 'react';

const columns = [
  {
    title: '区块高度',
    dataIndex: 'number',
    key: 'number',
  },
  {
    title: '区块哈希',
    dataIndex: 'hash',
    key: 'hash',
  },
  {
    title: '交易数',
    dataIndex: 'txCounts',
    key: 'txCounts',
  },
  {
    title: '交易平均处理时间(ms)',
    dataIndex: 'avgTime',
    key: 'avgTime',
  },
  {
    title: '出块时间',
    dataIndex: 'writeTime',
    key: 'writeTime',
    sorter: (a, b) => a.writeTime - b.writeTime,
  },
];

export default function HomePage() {
  // 定义当前页码和每页显示的数据项数目的状态变量
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  // 定义存储从后端获取的数据和总的数据项数目的状态变量
  const [data, setData] = useState([]);
  const [totalItems, setTotalItems] = useState(0);

  // 使用useEffect钩子，在组件加载时发送请求并获取数据
  useEffect(() => {
    fetchData(currentPage);
  }, [currentPage]);

  const fetchData = async (Page) => {
    try {
      const response = await request.post('/api/search', {
        params: {
          pageNum: Page,
        },
      });
      if (response.code === 200) {
        console.log(response);
        setData(response.data.blocks);
        console.log(response.data.blocks);
        setTotalItems(response.data.pages);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const handleChangePage = (page) => {
    setCurrentPage(page);
  };

  // const paginatedData = data.slice(
  // (currentPage - 1) * pageSize,
  // currentPage * pageSize
  // );
  console.log(data);
  return (
    <div className={styles.location}>
      <div>
        <Table columns={columns} dataSource={data} pagination={false} />
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={totalItems * 10}
          onChange={handleChangePage}
          className={styles.pageStyle}
          responsive
          showSizeChanger={false}
        />
      </div>
    </div>
  );
}
